package com.linkdood.app.web.rest;

import com.linkdood.app.dto.AttachmentDTO;
import com.linkdood.app.dto.UploadFileDTO;
import com.linkdood.app.exception.InvalidParamException;
import com.linkdood.app.service.AttachmentService;
import com.linkdood.app.service.UploadFileService;
import com.linkdood.app.utils.ResourceUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * Jssdk 文件上传
 */
@Api(value = "Jssdk文件接口", tags = {"Jssdk文件接口"})
@Slf4j
@RestController
@RequestMapping("/api/files")
public class UploadJssdkResource {

    @Value("${server.servlet.context-path}")
    private String contextPath;

    private final AttachmentService attachmentService;

    private final UploadFileService uploadFileService;

    public UploadJssdkResource(AttachmentService attachmentService, UploadFileService uploadFileService) {
        this.attachmentService = attachmentService;
        this.uploadFileService = uploadFileService;
    }

    // FIXME: 4/7/21 (syj) 返回的是缩略后的图片 url
    @ApiOperation(value = "上传图片，生成缩略图，并返回缩略图 url")
    @PostMapping("/images/upload")
    @ResponseBody
    public ResponseEntity<?> uploadImages(@Valid @RequestBody List<String> imageUrls) {
        if (imageUrls.isEmpty()) {
            throw new InvalidParamException();
        }
        List<String> result = new ArrayList<>();
        for (String imageUrl : imageUrls) {
            String[] args = imageUrl.split("\\.");
            if (args.length <= 1) {
                result.add(imageUrl);
                continue;
            }
            String end = args[args.length - 1];
            String randomUrl = UUID.randomUUID().toString();
            uploadFileService.uploadImages(imageUrl, randomUrl, end);
            result.add(contextPath + "/api/static-files/" + randomUrl + "." + end);
        }
        return ResponseEntity.ok(result);
    }

    @ApiOperation(value = "文件上传(Url上传)")
    @PostMapping("/upload")
    @ResponseBody
    public ResponseEntity<?> upload(@Valid @RequestBody List<AttachmentDTO> attachments) {
        if (attachments.isEmpty()) {
            throw new InvalidParamException();
        }
        Map<String, Boolean> temp = attachmentService.save(attachments);
        Map<String, Boolean> result = new HashMap<>(temp.size());
        List<String> ids = new ArrayList<>();
        for (Map.Entry<String, Boolean> entry : temp.entrySet()) {
            String key = entry.getKey();
            result.put(key.substring(0, key.lastIndexOf("-")), entry.getValue());
            ids.add(key.substring(key.lastIndexOf("-") +1));
        }
        attachmentService.downloadFile(ids);
        return ResponseEntity.ok(result);
    }

    @ApiOperation(value = "获取文件信息")
    @GetMapping("/all")
    @ResponseBody
    public ResponseEntity<?> getFiles(@RequestParam(value = "page", required = false) Integer page,
                                  @RequestParam(value = "size", required = false) Integer size,
                                  @RequestParam(value = "accountId", required = false) String accountId) {
        List<UploadFileDTO> uploadFiles = uploadFileService.listFilesByAccountId(page, size, accountId);
        return ResponseEntity.ok(uploadFiles);
    }

    @ApiOperation(value = "base64 编码文件上传")
    @PostMapping("/base64/upload")
    @ResponseBody
    public ResponseEntity<?> upload(@RequestBody Map<String, String> map) {
        String content = map.get("content");
        String name = map.get("name");
        String accountId = map.get("accountId");
        attachmentService.decryptByBase64(content, name, accountId);
        return ResponseEntity.ok(ResourceUtil.success());
    }

    @ApiOperation(value = "大文件上传")
    @PostMapping("/upload/base64")
    @ResponseBody
    public Map<String,String> uploadBase64(@RequestParam(value = "base64") String base64,
                                           @RequestParam(value = "burstSize") Long burst_size,
                                           @RequestParam(value = "fileIndex") Long file_index,
                                           @RequestParam(value = "fileNumber") Long file_number,
                                           @RequestParam(value = "fileId") String file_id,
                                           @RequestParam(value = "fileName") String file_name,
                                           @RequestParam(value = "fileHash") String file_hash
    ) throws IOException {
        return attachmentService.saveBase64(base64,burst_size,file_index,file_number,file_id,file_name,file_hash);
    }

}
